package com.md.youyouhui.ui.home;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.md.youyouhui.App;
import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityHomeInformationBinding;
import com.md.youyouhui.net.response.GetOilInfoResponse;
import com.md.youyouhui.net.response.HomeNewsResponse;
import com.md.youyouhui.net.response.IndexResponse;
import com.md.youyouhui.ui.BaseFragment;
import com.md.youyouhui.ui.adapter.InformationAdapter;
import com.md.youyouhui.utils.GlideImageLoader;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AdministratorZJ
 * on 2019/6/12.
 */
public class InformationFragment extends BaseFragment {
    private List<String> images = new ArrayList<>();
    private List<String> links = new ArrayList<>();
    private ActivityHomeInformationBinding informationBinding;
    private InformationAdapter adapter;
    private MainViewModel viewModel;
    int widths = 0;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = aMapLocation -> {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //可在其中解析amapLocation获取相应内容。
                String province = aMapLocation.getProvince();
                ToastUtils.makeText(getActivity(),province);
                informationBinding.location.setText(String.format("[%s]", province));
                informationBinding.location1.setText(String.format("[%s]", province));
                informationBinding.location2.setText(String.format("[%s]", province));
                String[] split = province.split("省");
                getLocationOil(split[0]);
                mLocationClient.stopLocation();
            } else {

                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                getLocationOil("浙江");
                //失败获取浙江
            }
        } else {
            Toast.makeText(mActivity, "定位失败,请查看权限是否开启", Toast.LENGTH_SHORT).show();
        }
    };
    private void initViewPager() {
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) informationBinding.banner.getLayoutParams();
        layoutParams.width = widths;
        layoutParams.height = (int) (widths / 1.8);
        informationBinding.banner.setLayoutParams(layoutParams);
        viewModel.index(1, 5).observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    IndexResponse data = listResource.data;
                    if (null == data) {
                        return;
                    }
                    for (int i = 0; i < data.rows.size(); i++) {
                        images.add(data.rows.get(i).cover);
                        links.add(data.rows.get(i).link);
                    }
                    showViewpage();
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }
    private void showViewpage() {
        /*homeBinding.banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        homeBinding.banner.setIndicatorGravity(BannerConfig.CENTER);*/
        informationBinding.banner.setDelayTime(3000);
        //设置图片源
        informationBinding.banner.setImages(images);
        informationBinding.banner.setImageLoader(new GlideImageLoader());
        //设置标题源
        //homeBinding.banner.setBannerTitles(titles);
        informationBinding.banner.start();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        informationBinding = DataBindingUtil.inflate(LayoutInflater.from(mActivity), R.layout.activity_home_information, container, false);
        viewModel = new MainViewModel();
        widths = mActivity.getWindowManager().getDefaultDisplay().getWidth();
        initView();
        initData();
        initViewPager();

        return informationBinding.getRoot();
    }

    public void initView() {


        informationBinding.ivMoreAct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, ActMoreActivity.class));

            }
        });
        informationBinding.ivSafe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, BannerViewActivity.class).putExtra("imageId", R.drawable.banner_long));
            }
        });
        informationBinding.ivGetCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, ReceiveOilActivity.class));
            }
        });
    }

    public void initData() {
        initLocation();
        adapter = new InformationAdapter(mActivity);
        informationBinding.infoRecycler.setAdapter(adapter);
        informationBinding.banner.setOnBannerListener(position -> {
            if ("share".equals(links.get(position))) {
                startActivity(new Intent(mActivity, BannerShareActivity.class));
            } else if ("security".equals(links.get(position))) {
                startActivity(new Intent(mActivity, BannerViewActivity.class).putExtra("imageId", R.drawable.banner_long));
            } else {
                startActivity(new Intent(mActivity, WebNewsActivity.class).putExtra("url", links.get(position)).putExtra("title", "详情"));
            }
        });
        getNews();
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(App.getContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
        // 如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void getLocationOil(String province) {
        viewModel.getOilInfo(province).observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    GetOilInfoResponse data = listResource.data;
                    if (null == data) {
                        return;
                    }
                    informationBinding.oil92.setText(data.ninety_two);
                    informationBinding.oil95.setText(data.ninety_five);
                    informationBinding.oil97.setText(data.ninety_eight);
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void getNews() {
        viewModel.getNews(1, 20).observe(this, homeNewsResponse -> {
            assert homeNewsResponse != null;
            switch (homeNewsResponse.status) {
                case LOADING:
                    informationBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    informationBinding.progress.setVisibility(View.GONE);
                    HomeNewsResponse data = homeNewsResponse.data;
                    if (null == data) {
                        return;
                    }
                    adapter.upDate(data.rows);
                    break;
                case ERROR:
                    informationBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(mActivity, homeNewsResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }



    @Override
    public void onDestroy() {

        super.onDestroy();
        informationBinding.banner.stopAutoPlay();
        //homeBinding.marqueeView.stopFlipping();
        //停止定位后，本地定位服务并不会被销毁
        mLocationClient.stopLocation();
        //销毁定位客户端，同时销毁本地定位服务。销毁定位客户端之后，若要重新开启定位请重新New一个AMapLocationClient对象。
        mLocationClient.onDestroy();
    }
}
